/**
 * API 类型定义
 * 与后端 Pydantic Schema 保持一致
 */

// ========== 通用类型 ==========
export interface PaginationParams {
  page: number
  page_size: number
}

export interface PaginatedResponse<T> {
  total: number
  items: T[]
  page: number
  page_size: number
}

// 统一 AI 标签类型，避免使用 any
export type AITags = Record<string, string | number | boolean>

// ========== 客户管理 ==========

// 客户需求类型
export type DemandType = 'rent_whole' | 'rent_shared' | 'rent_short' | 'buy' | 'sell'

// 客户来源渠道
export type SourceChannel = 'douyin' | 'wechat' | 'phone' | 'offline' | 'referral' | 'other'

// 客户跟进阶段
export type LeadStage =
  | 'new'
  | 'contacted'
  | 'viewing'
  | 'negotiating'
  | 'closed_won'
  | 'closed_lost'

// 客户质量等级 (MVP1)
export type QualityGrade = 'S' | 'A' | 'B' | 'C' | 'D'

// 与后端 LeadOut Schema 完全对齐
export interface Lead {
  id: number
  name: string
  phone: string
  demand_type: DemandType
  budget_range: string | null
  source_channel: SourceChannel
  stage: LeadStage
  notes: string | null
  tag_names: string | null // 标签名称（逗号分隔）："近地铁,学区房,安静"
  import_batch_id: string // UUID as string
  owner_id: number
  contacts_count: number
  notes_count: number
  ai_summaries_count: number

  // MVP1: 客户质量评分
  quality_score: number | null
  quality_grade: QualityGrade | null
  quality_updated_at: string | null // ISO datetime

  ai_tags?: AITags // AI 标签（可选，将废弃）
  created_at: string // ISO datetime
  updated_at: string // ISO datetime
}

export interface LeadCreate {
  name: string
  phone: string
  demand_type: DemandType
  budget_range?: string | null
  source_channel?: SourceChannel
  stage?: LeadStage
  notes?: string | null
  owner_id: number
  import_batch_id?: string // Optional, auto-generated if not provided
}

export interface LeadUpdate {
  name?: string
  phone?: string
  demand_type?: DemandType
  budget_range?: string | null
  source_channel?: SourceChannel
  stage?: LeadStage
  notes?: string | null
  owner_id?: number
}

// ========== 房源管理 ==========
export interface Property {
  id: number
  community_name: string
  address: string
  room_number: string
  layout: string
  rent_price: number
  landlord_phone: string
  status?: string
  area?: number
  floor?: string
  created_at: string
  updated_at: string
}

export interface PropertyCreate {
  community_name: string
  address: string
  room_number: string
  layout: string
  rent_price: number
  landlord_phone: string
  status?: string
  area?: number
  floor?: string
}

export interface PropertyUpdate {
  community_name?: string
  address?: string
  room_number?: string
  layout?: string
  rent_price?: number
  landlord_phone?: string
  status?: string
  area?: number
  floor?: string
}

// ========== 房源智能匹配 ==========
export interface MatchScoreBreakdown {
  budget_score: number
  layout_score: number
  area_score: number
  tag_score: number
  commute_score: number
  semantic_bonus: number
  total_score: number
}

export interface PropertyMatchResult {
  property_id: number
  property: Property
  match_score: number
  score_breakdown: MatchScoreBreakdown
  match_reasons: string[]
  mismatch_reasons: string[]
  ai_insights: string[]
}

export interface PropertyMatchListResponse {
  lead_id: number
  total_matched: number
  matches: PropertyMatchResult[]
  computed_at: string
}

export interface PropertyMatchParams {
  top_n?: number
  min_score?: number
  include_unavailable?: boolean
}

// ========== 访客单管理 ==========
export interface VisitorSheet {
  id: number
  lead_id: number
  property_id: number
  agent_id: number
  visit_date: string
  visit_time?: string
  duration_minutes?: number
  satisfaction?: number
  pros_tags?: string
  cons_tags?: string
  intention?: string
  notes?: string
  created_at: string
  updated_at: string
}

export interface VisitorSheetWithDetails extends VisitorSheet {
  lead_name?: string
  lead_phone?: string
  property_address?: string
  agent_name?: string
}

export interface VisitorSheetCreate {
  lead_id: number
  property_id: number
  agent_id: number
  visit_date: string
  visit_time?: string
  duration_minutes?: number
  satisfaction?: number
  pros_tags?: string
  cons_tags?: string
  intention?: string
  notes?: string
}

export interface VisitorSheetUpdate {
  visit_date?: string
  visit_time?: string
  duration_minutes?: number
  satisfaction?: number
  pros_tags?: string
  cons_tags?: string
  intention?: string
  notes?: string
}

// ========== 导入审核模块 ==========

// 导入批次状态
export type ImportStatus = 'processing' | 'completed' | 'failed'

// 导入记录状态
export type ImportRecordStatus = 'pending' | 'confirmed' | 'rejected' | 'error' | 'skipped'

// 导入批次信息 (与后端 ImportBatchOut 对齐)
export interface ImportBatch {
  id: string // UUID
  filename: string
  channel_hint: string | null
  record_count: number
  status: ImportStatus
  errors_count: number
  warnings_count: number
  duplicates_count: number
  imported_by: number
  created_at: string
  updated_at: string
}

// AI标签数据
export interface AITagData {
  tags: Array<{
    name: string
    confidence: number
  }>
  method: string
}

// 去重候选记录
export interface DuplicateCandidate {
  lead_id?: number
  record_id?: number
  score: number
  category: string
  match_type: string
}

// 导入记录 (与后端 ImportRecordOut 对齐)
export interface ImportRecord {
  id: number
  import_batch_id: string
  original_data: Record<string, unknown>
  normalized_data: Record<string, unknown>
  ai_tags: AITagData | null
  duplicate_candidates: {
    candidates: DuplicateCandidate[]
  } | null
  confidence: number
  status: ImportRecordStatus
  review_notes: string | null
  finalized: boolean
  finalized_lead_id: number | null
  created_at: string
  updated_at: string
}

// 导入记录更新参数
export interface ImportRecordUpdate {
  normalized_data?: Record<string, unknown>
  ai_tags?: AITagData | null
  duplicate_candidates?: {
    candidates: DuplicateCandidate[]
  } | null
  confidence?: number
  status?: ImportRecordStatus
  review_notes?: string | null
  finalized?: boolean
  finalized_lead_id?: number | null
}

// 批次统计信息
export interface ImportBatchStatistics {
  batch_id: string
  total_records: number
  status_breakdown: {
    pending: number
    confirmed: number
    rejected: number
    error: number
  }
  errors_count: number
  warnings_count: number
  duplicates_count: number
  average_confidence: number
}

// 批量操作请求
export interface BulkActionRequest {
  record_ids: number[]
  action: 'confirm' | 'reject'
}

// Finalize 结果
export interface FinalizeResult {
  finalized_count: number
  skipped_count: number
}

// ========== 用户认证 ==========
export interface LoginRequest {
  username: string
  password: string
  remember?: boolean // 记住我（30天自动登录）
}

export interface LoginResponse {
  access_token: string
  token_type: string
}

export interface PasswordResetDirectRequest {
  email: string
  new_password: string
  confirm_password: string
}

// 与后端 TokenPair 对齐
export interface TokenPair {
  access_token: string
  refresh_token: string
  token_type: string
  expires_at: string
}

// 与后端 UserOut Schema 完全对齐
export interface User {
  id: number
  email: string // 必填，邮箱
  full_name: string | null // 可选，用户全名
  role: 'admin' | 'project_manager' | 'consultant' | 'client' // 用户角色
  is_active: boolean // 账户是否激活
  is_admin: boolean // 是否为管理员
  created_at: string // 创建时间 (ISO格式)
  updated_at: string // 更新时间 (ISO格式)
}
